<?php

namespace app\api\controller;

use addons\third\library\Service;
use addons\third\library\Wechat;
use addons\third\model\Third;
use app\admin\model\express\Subscribe;
use app\api\model\TemplateSub;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login','get_accessToken','requestAPI','responseMsg1','push','curl','post2','get_token','responseMsg','mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wxappLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }


    //微信小程序消息推送配置 -- 配置服务器URL验证
    public function push(){
        if(request()->isPost()){
            $this->responseMsg1();
        }elseif (request()->get()){
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];

            $token = "abc123456abc";
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode( $tmpArr );
            $tmpStr = sha1( $tmpStr );

            if ($tmpStr == $signature ) {
                echo $_GET['echostr'];die;
            } else {
                return false;
            }
        }

    }

    public function responseMsg1(){
        $postStr = file_get_contents('php://input');   //此处推荐使用file_get_contents('php://input')获取后台post过来的数据
        $postArr = json_decode($postStr,true);

        $data = array(
            'MsgType'       => 'transfer_customer_service',
            'CreateTime'    => $postArr['CreateTime'],
            'ToUserName'    => $postArr['FromUserName'],
            'FromUserName'  => $postArr['ToUserName'],
//            'TransInfo'     => array(
//                'KfAccount'=>'aa@xx'//转发到指定客服
//            )
        );
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;


        if (!empty($postStr) && is_string($postStr)){
            $postArr = json_decode($postStr,true);

            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //用户发送文本消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $toUsername = $postArr['ToUserName'];   //发送者openid
                $CreateTime = $postArr['CreateTime'];   //发送者openid
              //  $json =  "<xml><ToUserName><![CDATA[$fromUsername]]></ToUserName><FromUserName><![CDATA[$toUsername]]></FromUserName><CreateTime>$CreateTime</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";


            //    echo $json;
 //die;




                $media_id = '';   //输入想要回复的图片消息的media_id
                $data=array(
                    "touser"=>$toUsername,
                    "fromuser"=>$fromUsername,
                    "createtime"=>$CreateTime,
                    "msgtype"=>'transfer_customer_service'
                );

           $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+
                $this->requestAPI($json);
            }elseif(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用户发送图文消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $media_id = '';   //输入想要回复的图片消息的media_id
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"image",
                    "image"=>array("media_id"=>$media_id)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4以上版本才可使用
                $this->requestAPI($json);
            }elseif($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用户进入客服
                $fromUsername = $postArr['FromUserName'];   //此处为文字回复，不同的回复方式可参考文章顶部第三个链接“回复客户消息”里查看
                $content = '你好,你的专属海报正在制作中,请稍后回复“1”获取海报';
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+
                $this->requestAPI($json);
            }else{
                exit('error');
            }
        }else{
            echo "empty";
            exit;
        }
    }

    public function requestAPI($json){

        $access_token = $this->get_accessToken();
        /*
         * POST发送https请求客服接口api
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($json)){
            curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);

        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        if($output == 0){
            echo 'success';exit;
        }
    }
    /* 调用微信api，获取access_token，有效期7200s*/
    public function get_accessToken(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx82e9d3c21e495f2c&secret=e38e9f79a06134d1d86eb73ae36df2eb'; //替换成自己的小程序id和secret
	$weixin = file_get_contents($url);
	$jsondecode = json_decode($weixin);
	$array = get_object_vars($jsondecode);
	$token = $array['access_token'];
	return $token;
    }



    public function responseMsg()
    {

        $postStr = file_get_contents('php://input');   //此处推荐使用file_get_contents('php://input')获取后台post过来的数据

        if (!empty($postStr) && is_string($postStr)){
            $postArr = json_decode($postStr,true);

            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //用户发送文本消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $content = '中文';   //输入想要回复
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //PHP版本5.4以上
                $this->post2($json);
            }else if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用户发送图文消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $media_id = '';   //输入想要回复的图片消息的media_id
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"image",
                    "image"=>array("media_id"=>$media_id)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);
                $this->post2($json);
            }else if($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用户进入客服
                $fromUsername = $postArr['FromUserName'];   //用户第一次进入客服系统
                $content = '吃了么！';
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);
                $this->post2($json);
            }else{
                exit('error');
            }
        }else{
            exit;
        }
    }


    //获取access_token/* 调用微信api，获取access_token，有效期7200s*/
    public function curl() {
        $appid="wx82e9d3c21e495f2c";
        $appsecret="e38e9f79a06134d1d86eb73ae36df2eb";
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret; //替换成自己的小程序id和secret
        $result = file_get_contents($url);
        $res = json_decode($result,true);   //json字符串转数组
        return $res['access_token'];
    }
    //更新access_token存储到数据库并返回数据
    public function get_token(){
    //    include("common.inc.php"); //这个是数据库链接信息，我是将token存储到数据库中。你可以根据自身情况修改
        $times=time();//当前时间
      //  $sql="select A_ID,A_Token,A_Date from wx_anran_accesstoken order by A_ID desc";
      //  $result = $conn->query($sql);

        if (count(Db::name('anran_accesstoken')->count()) > 0) {
            $row = Db::name('anran_accesstoken')->order('id desc')->find();
            if($row['date'] < $times){
                $token= $this->curl();
                $timestamp=time()+7100;
                Db::name('anran_accesstoken')->where('id',$row['id'])->update([
                    'token'=>$token,
                    'date'=>$timestamp
                ]);
               // $sqlu="UPDATE `wx_anran_accesstoken` SET `A_Token`='$token',`A_Date`='$timestamp' WHERE A_ID = '$row[A_ID]' ";
               // $conn->query($sqlu);
                return $token;
            }else{//没超过，则从数据库取
                return $row['A_Token'];
            }
        }else{
            $timestamp=time()+7100;
            $token= $this->curl();
            Db::name('anran_accesstoken')->insertGetId([
                'token'=>$token,
                'date'=>$timestamp
            ]);
            //$sqlin="insert into wx_anran_accesstoken(A_Token,A_Date) values('$token','$timestamp')";
          //  $conn->query($sqlin);
            return $token;
        }
    }
    //向客户端发送回复消息
    public function post2($data){
        $access_token = $this->get_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: text',
                'content' => $data
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        return $result;
    }





    /**
     * 会员中心
     */
    public function index()
    {
        $userinfo = $this->auth->getUserinfo();
        $userinfo['member_id'] = "XN".$userinfo['member_id'];
        $this->success('', $userinfo);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    // 小程序登陆
    public function wxappLogin(){
        $code = $this->request->post("code");
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        if (!$code) {
            $this->error("参数不正确");
        }
        // 获取配置
        $config = get_addon_config('third');
        $config = [
            'app_id'    => $config['wxapp']['app_id'],
            'secret'   => $config['wxapp']['app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $session = $app->auth->session($code);
        if (isset($session['openid'])) {
             $userInfo = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
            //如果有传Token
            $platform = 'wxapp';
            $result = [
                'openid'        => $session['openid'],
                'unionid'        => isset($userInfo['unionId']) ? $userInfo['unionId'] : '' ,
                'userinfo'      => [
                    'nickname' => filterEmoji($userInfo['nickName']),
                ],
                'access_token'  => $session['session_key'],
                'refresh_token' => '',
                'expires_in'    => isset($session['expires_in']) ? $session['expires_in'] : 0,
            ];
            //检测是否登录
            if ($this->auth->isLogin()) {
                $third = Third::where(['openid' => $session['openid'], 'platform' => 'wxapp'])->find();
                if ($third && $third['user_id'] == $this->auth->id) {
                    //把最新的 session_key 保存到 第三方表的 access_token 里
                    $third['access_token'] = $session['session_key'];
                    $third['unionid'] = isset($userInfo['unionId']) ? $userInfo['unionId'] : '' ;
                    $third->save();
                    $user = $this->auth->getUser();
                    $fields['gender'] = $userInfo['gender'];
                    $user->save($fields);
                    if(empty($user['member_id'])){
                        Db::name('user')->where('id',$user['id'])->update([
                            'member_id'=>str_pad($user['id'],5,"0",STR_PAD_LEFT)
                        ]);
                    }


                    $this->success("登录成功", $this->auth->getUserinfo());
                }elseif($third && $third['user_id'] !== $this->auth->id){
                    $this->success("登录失败,该微信已存在,请直接使用微信授权登陆");
                }else{
                    $time = time();
                    $values = [
                        'platform'      => $platform,
                        'openid'        => $result['openid'],
                        'openname'      => isset($result['userinfo']['nickname']) ? $result['userinfo']['nickname'] : '',
                        'access_token'  => $result['access_token'],
                        'refresh_token' => $result['refresh_token'],
                        'expires_in'    => $result['expires_in'],
                        'logintime'     => $time,
                        'expiretime'    => $time + $result['expires_in'],
                        'user_id'    => $this->auth->id,
                    ];
                    $auth = Auth::instance();
                    $user = $auth->getUser();
                    $fields = ['username' => 'u' . $user->id];
                    if (isset($result['userinfo']['nickname']))
                        $fields['nickname'] = $result['userinfo']['nickname'];
                    if (isset($result['userinfo']['avatar']))
                        $fields['avatar'] = $result['userinfo']['avatar'];
                    $fields['group_id'] = 0;
                    // 更新会员资料
                    $user->save($fields);
                    Third::create($values);
                    $userInfo = $auth->getUserinfo();
                    if(empty($userinfo['member_id'])){
                        Db::name('user')->where('id',$userinfo['id'])->update([
                            'member_id'=>str_pad($userinfo['id'],5,"0",STR_PAD_LEFT)
                        ]);
                    }
                    $userinfo['member_id'] = "XN".str_pad($userinfo['member_id'],5,"0",STR_PAD_LEFT);

                    $this->success("登录成功", ['userInfo' => $userinfo]);
                }
            }

            $extend = [
                'gender' => $userInfo['gender'],
                'nickname' => filterEmoji($userInfo['nickName']),
                'avatar' => $userInfo['avatarUrl'],
            ];
            $ret = Service::connect($platform, $result, $extend);
            if ($ret) {
                $auth = Auth::instance();
                $userinfo = $auth->getUserinfo();
                $userinfo['template'] = TemplateSub::TEMPLATE_LIST;
                if(empty($userinfo['member_id'])){
                    Db::name('user')->where('id',$userinfo['id'])->update([
                        'member_id'=>str_pad($userinfo['id'],5,"0",STR_PAD_LEFT)
                    ]);
                }
//                $userinfo['member_id'] = "XN".str_pad(Db::name('user')->where('id',$userinfo['id'])->value('member_id'),5,"0",STR_PAD_LEFT);
                $userinfo['member_id'] = $userinfo['id'];
                $this->test($userinfo['id']);
                $this->success("登录成功", ['userinfo' => $userinfo]);
            } else {
                $this->error("连接失败");
            }
        } else {
            $this->error("登录失败");
        }
        $this->error("登录失败");
    }

    public function test($user_id){

        $userInfo['id'] = $user_id;
        $count =  Db::name('coupon')->where('user_id',$userInfo['id'])->where('type','new')->count();
        if($count==0){
            $new =  \config('site.new');
            if($new>0){
                $id = Db::name('coupon')->insertGetId([
                    'user_id'=>$userInfo['id'],
                    'type'=>'new',
                    'title'=>'新人优惠券',
                    'money'=>$new,
                    'createtime'=>time(),
                    'day'=>\config('site.coupon_day'),
                    'expiry_time'=>time()+\config('site.coupon_day')*24*3600,
                ]);
            }
        }
    }


    //微信小程序订阅模板
    public function template(){
        $list = TemplateSub::TEMPLATE_LIST;
        $this->success('ok',$list);
    }




}
